package com.aiden.app.common.extension

import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import com.aiden.app.common.extension.ViewClickDelay.SPACE_TIME
import com.aiden.app.common.extension.ViewClickDelay.hash
import com.aiden.app.common.extension.ViewClickDelay.lastClickTime

/**
 * Descriptions：View 的一些扩展方法
 * <p>
 * Author：ChenME
 * Date：2019/3/5
 * Email：ibelieve1210@163.com
 */

object ViewClickDelay {
    var hash: Int = 0
    var lastClickTime: Long = 0
    var SPACE_TIME: Long = 1000
}


/**
 * 扩展 View 的点击事件
 */
fun View.onClick(listener: View.OnClickListener) {
    this.setOnClickListener(listener)
}

/**
 * 扩展 View 的点击事件
 */
fun View.onClick(isUseDelay: Boolean = true, method: () -> Unit) {
    this.setOnClickListener {
        if (isUseDelay) {
            if (hash != this.hashCode()) {
                hash = this.hashCode()
                lastClickTime = System.currentTimeMillis()
                method()
            } else {
                val currTime = System.currentTimeMillis()
                if (currTime - lastClickTime > SPACE_TIME) {
                    lastClickTime = System.currentTimeMillis()
                    method()
                }
            }
        } else {
            method()
        }
    }
}

/**
 * 扩展 View 的可见性
 */
fun View.setVisible(isShow: Boolean) {
    this.visibility = if (isShow) View.VISIBLE else View.GONE
}

/**
 * view是否可见
 */
fun View.isVisible(): Boolean {
    return this.visibility == View.VISIBLE
}

/**
 * 设置 View 的 Margin
 */
fun View.setMargin(left: Int, top: Int, right: Int, bottom: Int) {
    val lp = layoutParams as ViewGroup.MarginLayoutParams
    lp.setMargins(left, top, right, bottom)
    requestLayout()
}

fun EditText.catchText(): String {
    return this.text.toString().trim()
}